package org.zhaya.sdk.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.ReThrowConsoleErrorHandler;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.zhaya.sdk.constant.PipelineSawmillTypeEnum;
import org.zhaya.sdk.model.Condition;
import org.zhaya.sdk.model.PipelineModel;
import org.zhaya.sdk.model.PipelineNode;
import org.zhaya.sdk.processors.condition.ProcessorEnum;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author Ryan Yang
 * @Date 2022/10/10 4:27 下午
 */
@Slf4j
public class PipelineParseService {

    private static GroupTemplate GROUP_TEMPLATE;

    public synchronized static GroupTemplate getGroupTemplate() {
        if (Objects.isNull(GROUP_TEMPLATE)) {
            Configuration beetlConfiguration = null;
            try {
                beetlConfiguration = Configuration.defaultConfiguration();
                beetlConfiguration.setErrorHandlerClass(ReThrowConsoleErrorHandler.class.getName());
            } catch (IOException e) {
                log.error("template init error {}", e.getMessage(), e);
            }
            StringTemplateResourceLoader stringResourceLoader = new StringTemplateResourceLoader();
            GROUP_TEMPLATE = new GroupTemplate(stringResourceLoader, beetlConfiguration);
        }
        return GROUP_TEMPLATE;
    }

    /**
     * 模型校验/模型解析
     *
     * @param modelJson 模型json
     * @return 组件节点列表
     */
    public static List<PipelineNode> parse(String modelJson) {
        //校验modelJson不可缺省
        Assert.notBlank(modelJson, "model json can not be blank");

        //校验modelJson必须为Json格式
        Assert.isTrue(JSONUtil.isTypeJSON(modelJson), "model json is not json string");

        PipelineModel pipelineModel = JSONUtil.toBean(modelJson, PipelineModel.class);
        List<PipelineNode> pipelineNodeList = pipelineModel.getNodes();
        //校验nodes不可缺省
        Objects.requireNonNull(pipelineNodeList, "field[nodes] can not found in model json");

        pipelineNodeList = pipelineModel.getNodes().stream().filter(Objects::nonNull).collect(Collectors.toList());
        //校验nodes不可为空
        Assert.notEmpty(pipelineNodeList, "field[nodes] can not found in model json");

        Map<String, Long> nodeIdMap = pipelineNodeList.stream().collect(Collectors.groupingBy(PipelineNode::getNodeId, Collectors.counting()));
        nodeIdMap.forEach((nodeId, count) -> {
            //校验nodeId不可重复
            Assert.equals(count, 1L, "node[id: {}] is repeated", nodeId);
            nodeIdMap.put(nodeId, 0L);
        });
        Map<String, PipelineNode> nodeMap = pipelineNodeList.stream().collect(Collectors.toMap(PipelineNode::getNodeId, Function.identity()));
        String startNodeId = null;
        for (PipelineNode pipelineNode : pipelineNodeList) {
            //校验nodeId字段不可缺省
            Assert.notBlank(pipelineNode.getNodeId(), "any node needs to have a field[nodeId]");

            //校验name字段不可缺省
            Assert.notBlank(pipelineNode.getName(), "name of node[id: {}] is blank", pipelineNode.getNodeId());

            //校验type字段不可缺省
            Assert.notBlank(pipelineNode.getType(), "type of node[id: {}] is blank", pipelineNode.getNodeId());

            //校验组件类型存在
            Assert.isTrue(ProcessorManager.checkTypeExist(pipelineNode.getType()), "type of node[id: {}] is invalid", pipelineNode.getNodeId());

            //校验config字段不可缺省
            Assert.notBlank(pipelineNode.getConfig(), "config of node[id: {}] is blank", pipelineNode.getNodeId());

            //校验配置信息是否正确
            //校验起始节点至多一个
            if (CollUtil.isEmpty(pipelineNode.getParentNodeIds())) {
                Assert.isTrue(StrUtil.isBlank(startNodeId), "model json has more than one start nodes[{}, {}]", startNodeId, pipelineNode.getNodeId());
                startNodeId = pipelineNode.getNodeId();
            } else {
                pipelineNode.getParentNodeIds().forEach(parentNodeId -> {
                    //校验父节点不可为空
                    Assert.notBlank(parentNodeId, "parent node of node[id: {}] can not be blank", pipelineNode.getNodeId());
                    //校验父节点必须存在
                    Assert.isTrue(nodeIdMap.containsKey(parentNodeId), "parent node[id: {}] can not found in model json", parentNodeId);
                    nodeIdMap.put(parentNodeId, nodeIdMap.get(parentNodeId) + 1);
                    //除流程拆分组件外，其余组件只能做一次父节点
                    Assert.isTrue(ProcessorManager.checkIsIf(nodeMap.get(parentNodeId).getType()) || nodeIdMap.get(parentNodeId) < 2L, "node[id: {}] can not be the parent node repeatedly", parentNodeId);
                });
            }
        }
        //校验起始节点不可缺省
        Assert.notBlank(startNodeId, "can not found start node in model json");
        //校验结束结点不可缺省
        Assert.isTrue(nodeIdMap.values().stream().anyMatch(count -> count.equals(0L)), "can not found end node in model json");
        return pipelineNodeList;
    }

    /**
     * 根据组件列表转换为pipeline执行模板
     */
    public static String convertToConfig(List<PipelineNode> nodeList) {
        try {
            if (CollUtil.isEmpty(nodeList)) {
                return null;
            }
            List<String> steps = Lists.newArrayListWithExpectedSize(nodeList.size());
            for (PipelineNode pipeNode : nodeList) {
                if (ProcessorManager.checkIsSource(pipeNode.getType())) {
                    continue;
                }
                if (ProcessorManager.checkIsIf(pipeNode.getType())) {
                    String str = transferIfNode(pipeNode);
                    steps.add(str);
                    break;
                }
                Template nodeTemplate = getGroupTemplate().getTemplate(PipelineSawmillTypeEnum.NODE.template());
                nodeTemplate.binding("node", pipeNode);
                String nodeString = nodeTemplate.render();
                log.debug("convertToConfig node {} result {}", pipeNode, nodeString);
                steps.add(nodeString);
            }
            Template stepsTemplate = getGroupTemplate().getTemplate(PipelineSawmillTypeEnum.STEPS.template());
            stepsTemplate.binding("steps", steps);
            return stepsTemplate.render();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 转化流程拆分节点配置
     */
    private static String transferIfNode(PipelineNode ifNode) {
        List<Condition> conditions = ifNode.getConditions();
        List<Map<String, Object>> cases = Lists.newArrayList();
        for (Condition condition : conditions) {
            List<PipelineNode> childrenNodes = condition.getThen();
            List<String> childrenNodeSteps = Lists.newArrayList();
            if (CollUtil.isNotEmpty(childrenNodes)) {
                for (PipelineNode node : childrenNodes) {
                    if (node == null) {
                        continue;
                    }
                    if (ProcessorManager.checkIsIf(node.getType())) {
                        String ifNodeConfigStr = transferIfNode(node);
                        childrenNodeSteps.add(ifNodeConfigStr);
                        break;
                    } else {
                        Template nodeTemplate = getGroupTemplate().getTemplate(PipelineSawmillTypeEnum.NODE.template());
                        nodeTemplate.binding("node", node);
                        String nodeString = nodeTemplate.render();
                        childrenNodeSteps.add(nodeString);
                    }
                }
            }

            Map<String, Object> condition1 = condition.getCondition();
            Map<String, Object> caseTempMap = Maps.newHashMap();
            caseTempMap.put(ProcessorEnum.condition.name(), condition1);
            caseTempMap.put(ProcessorEnum.then.name(), childrenNodeSteps);
            cases.add(caseTempMap);
        }
        Template switchTemplate = getGroupTemplate().getTemplate(PipelineSawmillTypeEnum.SWITCH.template());
        switchTemplate.binding("cases", cases);
        return switchTemplate.render();
    }

    private static void transferIfNode(PipelineNode ifNode, Map<String, PipelineNode> nodesMap, Map<String, PipelineNode> realNodesMap, Map<String, PipelineNode> endNodeMap) {
        List<Condition> conditions = PipelineDebugService.getConditionListByConfig(ifNode.getConfig());
        for (Condition condition : conditions) {
            String nodeId = condition.getNodeId();
            List<PipelineNode> childrenNodes = condition.getThen();
            PipelineNode nextNode = realNodesMap.get(nodeId);
            if (childrenNodes == null) {
                childrenNodes = Lists.newArrayList();
            }
            if (endNodeMap.containsKey(nodeId)) {
                childrenNodes.add(nextNode);
                condition.setThen(childrenNodes);
                continue;
            }

            childrenNodes.add(nextNode);
            while (nextNode != null && nodesMap.containsKey(nodeId)) {
                if (ProcessorManager.checkIsIf(nextNode.getType())) {
                    transferIfNode(nextNode, nodesMap, realNodesMap, endNodeMap);
                    childrenNodes.add(nextNode);
                    break;
                } else {
                    nextNode = nodesMap.get(nodeId);
                    nodeId = nextNode.getNodeId();
                    childrenNodes.add(nextNode);
                }
            }
            condition.setThen(childrenNodes);
        }
        ifNode.setConditions(conditions);
    }

    public static void parse(List<PipelineNode> nodes) {
        Map<String, PipelineNode> nodesMap = Maps.newHashMap();
        Map<String, PipelineNode> realNodeMaps = Maps.newHashMap();
        for (PipelineNode node : nodes) {
            realNodeMaps.put(node.getNodeId(), node);
            List<String> parentNodeIds = node.getParentNodeIds();
            if (CollectionUtils.isNotEmpty(parentNodeIds)) {
                Set<String> parentNodeIdsSet = new HashSet<>(parentNodeIds);
                for (String parentNodeId : parentNodeIdsSet) {
                    nodesMap.put(parentNodeId, node);
                }
            }
        }
        if (CollUtil.isEmpty(nodesMap)) {
            return;
        }
        Map<String, PipelineNode> endNodeMap = nodes.stream().filter(node -> !nodesMap.containsKey(node.getNodeId()) && (CollectionUtils.isNotEmpty(node.getParentNodeIds()) && nodesMap.containsKey(node.getParentNodeIds().get(0)))).collect(Collectors.toMap(PipelineNode::getNodeId, node -> node));
        nodes.stream().filter(node -> ProcessorManager.checkIsIf(node.getType())).forEach(node -> transferIfNode(node, nodesMap, realNodeMaps, endNodeMap));
    }
}
